package com.leo.biz.service.pub;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.*;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by leo on 2016/11/4.
 */
public class TypeUtils {

    public static byte[] toBytes (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    public static String byte2String(byte[] bytes,String charSequence)
    {
        String ret=null;
        try {
             ret=new String(bytes,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            ret=null;
            e.printStackTrace();
        }
        return ret;
    }

    public static Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            // bytearray to object
            ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
            ObjectInputStream oi = new ObjectInputStream(bi);

            obj = oi.readObject();
            bi.close();
            oi.close();
        } catch (Exception e) {
            System.out.println("translation" + e.getMessage());
            e.printStackTrace();
        }
        return obj;
    }

    public static String map2Jsonstr(Map map)
    {
        Gson gson=new Gson();
        return gson.toJson(map,map.getClass());
    }

    public static Map json2Map(String str)
    {
        Gson gson=new Gson();
        return gson.fromJson(str, Map.class);
    }

    public static String list2Str(List<String> list,String separator)
    {
        String ret="";
        for(int i=0;i<list.size();i++)
        {
            ret=ret+separator+list.get(i);
        }
        return ret.length()==0?ret:ret.substring(1);
    }

    public static String object2Json(Object obj)
    {
        Gson gson=new Gson();
        return gson.toJson(obj,obj.getClass());
    }

    public static Object json2Object(String json,Type ss )
    {
        Gson gson=new Gson();
        Object obj= gson.fromJson(json,ss);
        return obj;
    }



}
